<template>
	<view class="content">
		<view class="navbar">
			<view 
				v-for="(item, index) in navList" :key="index" 
				class="nav-item" 
				:class="{current: tabCurrentIndex == index}"
				@click="tabClick(index)"
			>
			<view :class="{navItemBefore: tabCurrentIndex == index}"></view>
				{{item.text}}
			</view>
		</view>
		
		<swiper :current="tabCurrentIndex" class="swiper-box" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem,tabIndex) in navList" :key="tabIndex">
				<scroll-view 
					class="list-scroll-content" 
					scroll-y
					@scrolltolower="loadData"
				>
					<!-- 空白页 -->
					<empty v-if="tabItem.loaded === true && tabItem.orderList.length === 0"></empty>
					
					<!-- 订单列表 -->
					<view v-for="(item,index) in tabItem.orderList" :key="index" class="order-item">
						<view class="i-top b-b">
							<navigator v-if="storeType" :url="'/pages/Store/storeGoods?id='+item.store_id" class="time">{{item.store_name}}</navigator>
							<view v-else class="time">{{item.order_num}}</view>
							<text class="state" :style="{color: item.stateTipColor}">{{item.stateTip}}</text>
							<text 
								v-if="item.order_status == 10 || item.order_status == 5 || item.order_status == 6"
								class="del-btn yticon icon-iconfontshanchu1"
								@click="deleteOrder(item.order_num)"
							></text>
						</view>
						
						<scroll-view v-if="item.goods_list.length > 1" class="goods-box" @click="navToDetail(item)" scroll-x>
							<view
								v-for="(goodsItem, goodsIndex) in item.goods_list" :key="goodsIndex"
								class="goods-item"
							>
								<image class="goods-img" :src="goodsItem.order_goods_img" mode="aspectFill"></image>
							</view>
						</scroll-view>
						<view 
							v-if="item.goods_list.length === 1" 
							class="goods-box-single"
							v-for="(goodsItem, goodsIndex) in item.goods_list" :key="goodsIndex"
							@click="navToDetail(item)"
						>
							<image class="goods-img" :src="goodsItem.order_goods_img" mode="aspectFill"></image>
							<view class="right">
								<text class="title clamp">{{goodsItem.order_goods_name}}</text>
								<text class="attr-box">{{goodsItem.order_goods_spec}}  x {{goodsItem.order_goods_num}}</text>
								<text class="price">{{goodsItem.order_goods_price}}</text>
							</view>
						</view>
						
						<view class="price-box">
							<!-- 共<text class="num">7</text>件商品 -->
							 实付款
							<text class="price">{{Number(item.order_money)+Number(item.consignee_money)}}</text>
							<!-- <span v-if="item.consignee_money>0">(含运费:￥{{item.consignee_money}})</span> -->
						</view>
						<view class="action-box b-t" v-if="item.order_status == 1">
							<button class="action-btn" @click="cancelOrder(item.order_num)">取消订单</button>
							<button :style="{background:themes.Backgroundshallow,color:themes.BtnColor,borderColor:themes.BtnBorder}" class="action-btn recom" @click="payOrder(item)">立即支付</button>
						</view>
						<!-- <view class="action-box b-t" v-if="item.order_status == 2">
							<button class="action-btn" @click="afterSale(item)">申请退款</button>
							<button :style="{background:themes.Backgroundshallow,color:themes.BtnColor,borderColor:themes.BtnBorder}" class="action-btn recom" @click="txFahuo(item.order_num)">提醒发货</button>
						</view> -->
						<view class="action-box b-t" v-if="item.order_status == 3">
							<!-- <button class="action-btn" @click="afterSale(item)">申请退款</button>
							<button class="action-btn" @click="logistics(item.order_num)">查看物流</button> -->
							<button :style="{background:themes.Backgroundshallow,color:themes.BtnColor,borderColor:themes.BtnBorder}" class="action-btn recom" @click="receipt_before(item.order_num,item)">确认收货</button>
						</view>
						<view class="action-box b-t" v-if="item.order_status == 4">
							<button :style="{background:themes.Backgroundshallow,color:themes.BtnColor,borderColor:themes.BtnBorder}" class="action-btn recom" @click="deleteOrder(item.order_num)">删除订单</button>
							<!-- <button class="action-btn" @click="logistics(item.order_num)">查看物流</button> -->
							<!-- <button :style="{background:themes.Backgroundshallow,color:themes.BtnColor,borderColor:themes.BtnBorder}" class="action-btn recom" @click="NavtoPingjia(item)">评价</button> -->
						</view>
					</view>
					 
					<uni-load-more :statusText="tabItem.statusText" :status="tabItem.loadingType"></uni-load-more>
					
				</scroll-view>
			</swiper-item>
		</swiper>
		<u-popup v-model="show" mode="center" border-radius="14" width="90%" :closeable="true">
			<view class="popup-head">
				{{logisticList.company}} {{logisticList.LogisticCode}} <u-icon @click="setClipboardData(logisticList.LogisticCode)" name="tags" color="#999999" size="28"></u-icon>
			</view>
			<uni-steps style="padding: 30upx;"
			:options="logisticList.Traces"
			direction="column" :active="0">
			</uni-steps>
		</u-popup>
		<u-popup mode="bottom" :safe-area-inset-bottom="true" v-model="shows">
			<KeyNumber @key="trueOrder" @NavTo="NavTo" ref="child" :show="true" :show2="true"></KeyNumber>
		</u-popup>
	</view>
</template>

<script>
	import uniLoadMore from './components/uni-load-more/uni-load-more.vue';
	import empty from "./components/empty";
	import uniSteps from './components/uni-steps/uni-steps.vue';
	import KeyNumber from './components/KeyNumber.vue'
	import { mapState } from 'vuex'; 
	export default {
		components: {
			uniLoadMore,
			empty,
			uniSteps,
			KeyNumber
		},
		computed: {
			...mapState(['themes'])
		},
		data() {
			return {
				tabCurrentIndex: 0,
				navList: [{
						state: 0,
						text: '全部',
						loadingType: 'more',
						loaded:'',
						statusText:false,
						orderList: [],
						page:1,
					},
					{
						state: 1,
						text: '待付款',
						loadingType: 'more',
						loaded:'',
						statusText:false,
						orderList: [],
						page:1,
					},
					{
						state: 3,
						text: '已支付',
						loadingType: 'more',
						loaded:'',
						statusText:false,
						orderList: [],
						page:1,
					},
					{
						state: 4,
						text: '已完成',
						loadingType: 'more',
						loaded:'',
						statusText:false,
						orderList: [],
						page:1,
					}
				],
				page_size:10,
				keyword:'',
				show:false,
				shows:false,
				logisticList:{
					company:'',
					LogisticCode:'',
					Traces:[],
				},
				id:"",
				item:"",
				storeType:true,
			};
		},
		onShow(){
			this.navList=[{
					state: 0,
					text: '全部',
					loadingType: 'more',
					loaded:'',
					statusText:false,
					orderList: [],
					page:1,
				},
				{
					state: 1,
					text: '待付款',
					loadingType: 'more',
					loaded:'',
					statusText:false,
					orderList: [],
					page:1,
				},
				{
					state: 3,
					text: '已支付',
					loadingType: 'more',
					loaded:'',
					statusText:false,
					orderList: [],
					page:1,
				},
				{
					state: 4,
					text: '已完成',
					loadingType: 'more',
					loaded:'',
					statusText:false,
					orderList: [],
					page:1,
				}
			]
			this.loadData();
		},
		onLoad(options){
			/**
			 * 修复app端点击除全部订单外的按钮进入时不加载数据的问题
			 * 替换onLoad下代码即可
			 */
			this.tabCurrentIndex = options.state;
			// #ifndef MP
			this.loadData()
			// #endif
			// #ifdef MP
			if(options.state == 0){
				this.loadData()
			}
			// #endif
		},
		methods: {
			//获取订单列表
			loadData(source){
				//这里是将订单挂载到tab列表下
				let index = Number(this.tabCurrentIndex);
				let navItem = this.navList[index];
				let state = navItem.state;
				
				if(source === 'tabChange'){
					if(navItem.loaded === true){
						//tab切换只有第一次需要加载数据
						return;
					}else{
						navItem.orderList = [];
					}
				}
				if(navItem.loadingType === 'loading'){
					//防止重复加载
					return;
				}
				navItem.loadingType = 'loading';
				
				this.$https.Order.getOrderList(state,navItem.page,this.page_size).then(res => {
					uni.stopPullDownRefresh();
					let orderList = res.order;
					if(orderList.length==0){
						navItem.loadingType = 'noMore';
						this.$set(navItem, 'loaded', true);
						return false;
					}
					orderList.forEach(item=>{
						navItem.orderList.push(item);
					})
					navItem.lastPage = res.count_page;
					orderList.filter(item=>{
						//添加不同状态下订单的表现形式
						item = Object.assign(item, this.orderStateExp(item.order_status));
					});
					
					//loaded新字段用于表示数据加载完毕，如果为空可以显示空白页
					this.$set(navItem, 'loaded', true);
					//判断是否还有数据， 有改为 more， 没有改为noMore 
					navItem.page++;
					navItem.loadingType = navItem.page >= navItem.lastPage ? 'noMore' : 'more';
					if(navItem.lastPage == 1){
						navItem.statusText = true;
					}
				});
			},

			//swiper 切换
			changeTab(e){
				this.tabCurrentIndex = e.target.current;
				this.loadData('tabChange');
			},
			//顶部tab点击
			tabClick(index){
				this.tabCurrentIndex = index;
			},
			//删除订单
			deleteOrder(id){
				uni.showModal({
				    content: '是否确定删除这条订单',
				    success: e => {
				        if (e.confirm) {
							this.del(id);
				        }
				    }
				})
			},
			del(id){
			    uni.showLoading({
			    	title: '请稍后'
			    })
				this.$https.Order.deleteOrder(id).then(res => {
					let list = this.navList[0].orderList;
					let index = list.findIndex(val=>val.order_num == id);
					index !== -1 && list.splice(index, 1);
					
					let list2 = this.navList[4].orderList;
					let index2 = list2.findIndex(val=>val.order_num == id);
					index2 !== -1 && list2.splice(index2, 1);
					uni.hideLoading();
					uni.showToast({
						title:'订单已删除',
						icon:'none'
					})
				})
			},
			//取消订单
			cancelOrder(id){
				uni.showModal({
				    content: '是否确定取消这条订单',
				    success: e => {
				        if (e.confirm) {
				            this.cancel(id);
				        }
				    }
				})
			},
			cancel(id){
				uni.showLoading({
				    title: '请稍后'
				})
				this.$https.Order.cancelOrder(id).then(res => {
					let {stateTip, stateTipColor} = this.orderStateExp(5);
					
					//取消订单后删除待付款中该项
					let list = this.navList[1].orderList;
					let index = list.findIndex(val=>val.order_num == id);
					index !== -1 && list.splice(index, 1);
					//取消订单后修改全部订单中该项的状态 
					let list2 = this.navList[0].orderList;
					let index2 = list2.findIndex(val=>val.order_num == id);
					if(index2!== -1){
						list2[index2] = Object.assign(list2[index2], {
							order_status: 5,
							stateTip, 
							stateTipColor
						})
					}
					uni.hideLoading();
					uni.showToast({
						title:'订单已取消',
						icon:'none'
					})
				})
			},
			//付款
			payOrder(item){
				uni.navigateTo({
					url: `/pages/Order/pay?order=${item.order_num}&money=${Number(item.order_money)+Number(item.consignee_money)}&type=1`
				})
			},
			//申请退款
			afterSale(item){
				uni.navigateTo({
					url:'/pages/Order/aftersale?item='+JSON.stringify(item)
				})
			},
			//提醒发货
			txFahuo(orderid){
				uni.showModal({
				    content: '是否提醒卖家发货',
				    success: e => {
				        if (e.confirm) {
				            uni.showLoading({
				            	title: '请稍后'
				            })
				            this.$https.Order.RemindDelivery(orderid).then(res => {
								uni.hideLoading();
								this.$api.msg('已提醒发货')
							})
				        }
				    }
				})
			},
			receipt_before(id,item){
				uni.showModal({
				    content: '是否确认收货',
				    success: e => {
				        if (e.confirm) {
							// this.shows = true;
							// this.id = id;
							// this.item = item;
							this.receipt(id,item);
				        }
				    }
				})
			},
			NavTo(){
				uni.navigateTo({
					url:'/pages/Member/safe/userpass'
				})
			},
			trueOrder(key){
				uni.showLoading({
					title: '请稍后'
				})
				this.$https.Order.checkPayPassword(key).then(res => {
					if(this.$refs.child){
						this.$refs.child.password = '';
						this.$refs.child.close();
					}
					this.shows = false;
					this.receipt(this.id,this.item);
				}).catch(fail=>{
					// uni.hideLoading(); 
					if(this.$refs.child){
						this.$refs.child.password = '';
						this.$refs.child.close();
					}
				});
			},
			//确认收货
			receipt(id,item){
				this.$https.Order.receipt(id).then(res => {
					let {stateTip} = this.orderStateExp(4);
					//确认收货后修改待收货中该项的状态
					let list = this.navList[3].orderList;
					let index = list.findIndex(val=>val.order_num == id);
					index !== -1 && list.splice(index, 1);
					//确认收货后修改全部订单中该项的状态 
					let list2 = this.navList[0].orderList;
					let index2 = list2.findIndex(val=>val.order_num == id);
					if(index2!== -1){
						list2[index2] = Object.assign(list2[index2], {
							order_status: 4,
							stateTip
						})
					}
					//确认收货后添加到待评价列表中
					item = Object.assign(item, {
						order_status: 4,
						stateTip
					})
					this.navList[4].orderList.push(item);
					uni.hideLoading();
					this.$api.msg('已确认收货')
				})
			},
			//查看物流
			logistics(id){
				this.$https.Order.query(id).then(res => {
					this.logisticList = res;
					this.show = true;
				})
			},
			//订单详情
			navToDetail(item){
				uni.navigateTo({
					url: `/pages/Order/orderDetails?order_id=${item.order_num}&status=${item.order_status}`
				})
			},
			//发表评价
			NavtoPingjia(item){
				uni.navigateTo({
					url: `/pages/Order/evaluation?order=${JSON.stringify(item)}`
				})
			},
			//评价发表后数据处理
			NextPingjia(id){
				let {stateTip,stateTipColor} = this.orderStateExp(10);
				//评价发表后删除待评价中该项
				let list = this.navList[4].orderList;
				let index = list.findIndex(val=>val.id == id);
				index !== -1 && list.splice(index, 1);
				//评价发表后修改全部订单中该项的状态 
				let list2 = this.navList[0].orderList;
				let index2 = list2.findIndex(val=>val.id == id);
				if(index2!== -1){
					list2[index2] = Object.assign(list2[index2], {
						order_status:10,
						stateTip,
						stateTipColor
					})
				}
			},
			//订单状态文字和颜色
			orderStateExp(status){
				let stateTip = '',
					stateTipColor = this.themes.FrontColor;
				switch(+status){
					case 1:
						stateTip = '待付款'; break;
					case 2:
						stateTip = '待发货'; break;
					case 3:
						stateTip = '已支付'; break;
					case 4:
						stateTip = '已完成'; break;
					case 10:
						stateTip = '订单已完成'; 
						stateTipColor = '#909399';
						break;
					case 5:
						stateTip = '订单已关闭';
						stateTipColor = '#909399';
						break;
					case 6:
						stateTip = '订单已关闭';
						stateTipColor = '#909399';
						break;
					//更多自定义
				}
				return {stateTip, stateTipColor};
			},
			setClipboardData(data) {
				return new Promise((success, fail) => {
					// #ifndef H5
					uni.setClipboardData({ data, success, fail });
					// #endif
			
					// #ifdef H5
					// navigator.clipboard.writeText(data).then(success).catch(fail);
					const textarea = document.createElement('textarea');
					textarea.value = data;
					textarea.readOnly = 'readOnly';
					document.body.appendChild(textarea);
					textarea.select();
					textarea.setSelectionRange(0, data.length);
					document.execCommand('copy');
					textarea.remove();
					success(data);
					// #endif
					uni.showToast({
						title:'复制成功',
						icon:'none'
					})
				});
			}
		},
	}
</script>

<style lang="scss">
	.u-drawer /deep/ .u-mode-center-box{
		max-height: 90%;
	}
	.popup-head{
		width: 100%;
		height: 80upx;
		line-height: 80upx;
		padding-left: 30upx;
		background: #eee;
	}
	page, .content{
		background: #f8f8f8;
		height: 100%;
	}
	.content /deep/ .uni-swiper-wrapper{
		overflow: auto;
		// min-height: 100vh;
	}
	.swiper-box{
		height: calc(100% - 40px);
	}
	.list-scroll-content{
		height: 100%;
	}
	
	.navbar{
		display: flex;
		height: 40px;
		padding: 0 5px;
		background: #fff;
		box-shadow: 0 1px 5px rgba(0,0,0,.06);
		position: relative;
		z-index: 10;
		.nav-item{
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 15px;
			color: #303133;
			position: relative;
			&.current{
				color: $uni-color-primary;
				// &:after{
				// 	content: '';
				// 	position: absolute;
				// 	left: 50%;
				// 	bottom: 0;
				// 	transform: translateX(-50%);
				// 	width: 44px;
				// 	height: 0;
				// 	border-bottom: 2px solid $uni-color-primary;
				// }
			}
			.navItemBefore{
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 44px;
					height: 0;
					border-bottom: 2px solid $uni-color-primary;
			}
		}
	}

	.uni-swiper-item{
		height: auto;
	}
	.order-item{
		display: flex;
		flex-direction: column;
		padding-left: 30upx;
		background: #fff;
		margin-top: 16upx;
		.i-top{
			display: flex;
			align-items: center;
			height: 80upx;
			padding-right:30upx;
			font-size: $uni-font-size-base;
			color: #303133;
			position: relative;
			.time{
				flex: 1;
			}
			.state{
				color: $uni-color-primary;
			}
			.del-btn{
				padding: 10upx 0 10upx 36upx;
				font-size: $uni-font-size-lg;
				color: #909399;
				position: relative;
				&:after{
					content: '';
					width: 0;
					height: 30upx;
					border-left: 1px solid #DCDFE6;
					position: absolute;
					left: 20upx;
					top: 50%;
					transform: translateY(-50%);
				}
			}
		}
		/* 多条商品 */
		.goods-box{
			height: 160upx;
			padding: 20upx 0;
			white-space: nowrap;
			.goods-item{
				width: 120upx;
				height: 120upx;
				display: inline-block;
				margin-right: 24upx;
			}
			.goods-img{
				display: block;
				width: 100%;
				height: 100%;
			}
		}
		/* 单条商品 */
		.goods-box-single{
			display: flex;
			padding: 20upx 0;
			.goods-img{
				display: block;
				width: 120upx;
				height: 120upx;
			}
			.right{
				flex: 1;
				display: flex;
				flex-direction: column;
				padding: 0 30upx 0 24upx;
				overflow: hidden;
				.title{
					font-size: $uni-font-size-base + 2rpx;
					color: #303133;
					line-height: 1;
				}
				.attr-box{
					font-size: $uni-font-size-sm + 2rpx;
					color: #909399;
					padding: 10upx 12upx;
				}
				.price{
					font-size: $uni-font-size-base + 2rpx;
					color: #303133;
					&:before{
						content: '￥';
						font-size: $uni-font-size-sm;
						margin: 0 2upx 0 8upx;
					}
				}
			}
		}
		
		.price-box{
			display: flex;
			justify-content: flex-end;
			align-items: baseline;
			padding: 20upx 30upx;
			font-size: $uni-font-size-sm + 2rpx;
			color: #909399;
			.num{
				margin: 0 8upx;
				color: #303133;
			}
			.price{
				font-size: $uni-font-size-lg;
				color: #303133;
				&:before{
					content: '￥';
					font-size: $uni-font-size-sm;
					margin: 0 2upx 0 8upx;
				}
			}
		}
		.action-box{
			display: flex;
			justify-content: flex-end;
			align-items: center;
			height: 100upx;
			position: relative;
			padding-right: 30upx;
		}
		.action-btn{
			width: 160upx;
			height: 60upx;
			margin: 0;
			margin-left: 24upx;
			padding: 0;
			text-align: center;
			line-height: 60upx;
			font-size: $font-sm + 2rpx;
			color: $font-color-dark;
			background: #fff;
			border-radius: 100px;
			border: 1upx solid rgba(0,0,0,.2);
			&:after{
				display: none;
				border-radius: 100px;
			}
			&.recom{
				background: #fff9f9;
				color: $base-color;
				// &:after{
				// 	border-color: #f7bcc8;
				// }
			}
		}
	}
	
	
	/* load-more */
	.uni-load-more {
		display: flex;
		flex-direction: row;
		height: 80upx;
		align-items: center;
		justify-content: center
	}
	
	.uni-load-more__text {
		font-size: 28upx;
		color: #999
	}
	
	.uni-load-more__img {
		height: 24px;
		width: 24px;
		margin-right: 10px
	}
	
	.uni-load-more__img>view {
		position: absolute
	}
	
	.uni-load-more__img>view view {
		width: 6px;
		height: 2px;
		border-top-left-radius: 1px;
		border-bottom-left-radius: 1px;
		background: #999;
		position: absolute;
		opacity: .2;
		transform-origin: 50%;
		animation: load 1.56s ease infinite
	}
	
	.uni-load-more__img>view view:nth-child(1) {
		transform: rotate(90deg);
		top: 2px;
		left: 9px
	}
	
	.uni-load-more__img>view view:nth-child(2) {
		transform: rotate(180deg);
		top: 11px;
		right: 0
	}
	
	.uni-load-more__img>view view:nth-child(3) {
		transform: rotate(270deg);
		bottom: 2px;
		left: 9px
	}
	
	.uni-load-more__img>view view:nth-child(4) {
		top: 11px;
		left: 0
	}
	
	.load1,
	.load2,
	.load3 {
		height: 24px;
		width: 24px
	}
	
	.load2 {
		transform: rotate(30deg)
	}
	
	.load3 {
		transform: rotate(60deg)
	}
	
	.load1 view:nth-child(1) {
		animation-delay: 0s
	}
	
	.load2 view:nth-child(1) {
		animation-delay: .13s
	}
	
	.load3 view:nth-child(1) {
		animation-delay: .26s
	}
	
	.load1 view:nth-child(2) {
		animation-delay: .39s
	}
	
	.load2 view:nth-child(2) {
		animation-delay: .52s
	}
	
	.load3 view:nth-child(2) {
		animation-delay: .65s
	}
	
	.load1 view:nth-child(3) {
		animation-delay: .78s
	}
	
	.load2 view:nth-child(3) {
		animation-delay: .91s
	}
	
	.load3 view:nth-child(3) {
		animation-delay: 1.04s
	}
	
	.load1 view:nth-child(4) {
		animation-delay: 1.17s
	}
	
	.load2 view:nth-child(4) {
		animation-delay: 1.3s
	}
	
	.load3 view:nth-child(4) {
		animation-delay: 1.43s
	}
	
	@-webkit-keyframes load {
		0% {
			opacity: 1
		}
	
		100% {
			opacity: .2
		}
	}
</style>
